<template>
    <div class="complaint-management">
        <!-- 操作栏 -->
        <div class="operation-bar">
            <el-input
                v-model="searchText"
                placeholder="搜索投诉编号/投诉人/礼物类型"
                style="width: 300px"
                clearable
            >
                <template #prefix>
                    <span style="margin-right: 8px">🔍</span>
                </template>
            </el-input>
            <el-button type="primary" @click="handleAdd">
                <span style="margin-right: 5px">+</span>新建投诉
            </el-button>
        </div>

        <!-- 数据表格 -->
        <el-table :data="filteredComplaints" border style="width: 100%">
            <el-table-column prop="complaintId" label="投诉编号" width="180" sortable />
            <el-table-column prop="customer" label="投诉人" width="120" />
            <el-table-column prop="giftType" label="礼物类型" width="150">
                <template #default="{ row }">
                    <el-tag type="info">{{ row.giftType }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="submitDate" label="提交时间" width="150">
                <template #default="{ row }">
                    {{ formatDate(row.submitDate) }}
                </template>
            </el-table-column>
            <el-table-column prop="content" label="投诉内容" width="200">
                <template #default="{ row }">
                    <span v-if="row.content.length > 20">{{ row.content.slice(0, 20) }}...</span>
                    <span v-else>{{ row.content }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="status" label="处理状态" width="120">
                <template #default="{ row }">
                    <el-tag :type="statusType[row.status]">
                        {{ statusOptions.find(s => s.value === row.status)?.label }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
                <template #default="{ row }">
                    <el-button size="small" @click="handleEdit(row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="handleDelete(row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 添加/编辑对话框 -->
        <el-dialog
            v-model="dialogVisible"
            :title="isEditMode ? '编辑投诉记录' : '新建投诉'"
            width="600"
        >
            <el-form
                ref="formRef"
                :model="formData"
                :rules="formRules"
                label-width="80px"
            >
                <el-form-item label="投诉编号" prop="complaintId">
                    <el-input v-model="formData.complaintId" :disabled="isEditMode" />
                </el-form-item>
                <el-form-item label="投诉人" prop="customer">
                    <el-input v-model="formData.customer" />
                </el-form-item>
                <el-form-item label="礼物类型" prop="giftType">
                    <el-select v-model="formData.giftType" placeholder="请选择类型">
                        <el-option
                            v-for="item in giftTypes"
                            :key="item"
                            :label="item"
                            :value="item"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="提交时间" prop="submitDate">
                    <el-date-picker
                        v-model="formData.submitDate"
                        type="datetime"
                        placeholder="选择日期时间"
                        value-format="YYYY-MM-DD HH:mm:ss"
                    />
                </el-form-item>
                <el-form-item label="投诉内容" prop="content">
                    <el-input type="textarea" v-model="formData.content" rows="3" />
                </el-form-item>
                <el-form-item label="处理状态" prop="status">
                    <el-select v-model="formData.status" placeholder="请选择状态">
                        <el-option
                            v-for="item in statusOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitForm">确认</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, computed, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 日期格式化（包含时间）
const formatDate = (dateString) => {
    if (!dateString) return ''
    const date = new Date(dateString)
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    }).replace(/\//g, '-')
}

// 礼物类型（参考网页4的礼品分类）
const giftTypes = [
    '鲜花礼盒',
    '创意首饰',
    '定制礼品',
    '情侣对戒',
    '节日礼盒',
    '文创产品'
]

// 处理状态选项（根据网页1的流程优化）
const statusOptions = [
    { value: 0, label: '待核实' },
    { value: 1, label: '处理中' },
    { value: 2, label: '已解决' }
]
const statusType = { 0: 'danger', 1: 'warning', 2: 'success' }

// 10条投诉测试数据（基于网页1和网页4的案例）
const complaints = ref([
    {
        id: 1,
        complaintId: 'GF202405001',
        customer: '张女士',
        giftType: '鲜花礼盒',
        submitDate: '2024-05-15 14:30:00',
        content: '收到的玫瑰花束有半数花朵枯萎，与宣传图片严重不符',
        status: 0
    },
    {
        id: 2,
        complaintId: 'GF202405002',
        customer: '李先生',
        giftType: '情侣对戒',
        submitDate: '2024-05-16 10:15:00',
        content: '戒指尺寸与定制要求不符，内壁刻字存在错别字',
        status: 1
    },
    {
        id: 3,
        complaintId: 'GF202405003',
        customer: '王先生',
        giftType: '定制礼品',
        submitDate: '2024-05-17 15:45:00',
        content: '定制水晶摆件存在明显划痕，包装盒破损严重',
        status: 2
    },
    {
        id: 4,
        complaintId: 'GF202405004',
        customer: '赵小姐',
        giftType: '创意首饰',
        submitDate: '2024-05-18 09:30:00',
        content: '项链锁扣存在质量问题，佩戴当天即断裂',
        status: 0
    },
    {
        id: 5,
        complaintId: 'GF202405005',
        customer: '陈同学',
        giftType: '节日礼盒',
        submitDate: '2024-05-19 16:20:00',
        content: '中秋礼盒内月饼过期，生产日期标签被篡改',
        status: 1
    },
    {
        id: 6,
        complaintId: 'GF202405006',
        customer: '周女士',
        giftType: '文创产品',
        submitDate: '2024-05-20 11:00:00',
        content: '故宫文创书签镀金层脱落，存在以次充好嫌疑',
        status: 2
    },
    {
        id: 7,
        complaintId: 'GF202405007',
        customer: '吴先生',
        giftType: '鲜花礼盒',
        submitDate: '2024-05-21 17:10:00',
        content: '承诺的99朵玫瑰实际只收到72朵，配送延误3小时',
        status: 0
    },
    {
        id: 8,
        complaintId: 'GF202405008',
        customer: '郑女士',
        giftType: '定制礼品',
        submitDate: '2024-05-22 08:45:00',
        content: '定制照片抱枕颜色严重偏色，面料起球严重',
        status: 1
    },
    {
        id: 9,
        complaintId: 'GF202405009',
        customer: '孙先生',
        giftType: '情侣对戒',
        submitDate: '2024-05-23 13:30:00',
        content: '承诺的铂金材质实际检测为合金，涉嫌虚假宣传',
        status: 2
    },
    {
        id: 10,
        complaintId: 'GF202405010',
        customer: '林女士',
        giftType: '节日礼盒',
        submitDate: '2024-05-24 14:00:00',
        content: '情人节巧克力礼盒内商品融化变形，保温措施缺失',
        status: 0
    }
])

// 搜索功能（支持多字段模糊搜索）
const searchText = ref('')
const filteredComplaints = computed(() => {
    const searchKey = searchText.value.toLowerCase()
    return complaints.value.filter(complaint => {
        return [
            complaint.complaintId,
            complaint.customer,
            complaint.giftType,
            complaint.content
        ].join('').toLowerCase().includes(searchKey)
    })
})

// 对话框状态管理
const dialogVisible = ref(false)
const isEditMode = ref(false)
const formRef = ref(null)
const formData = reactive({
    id: null,
    complaintId: '',
    customer: '',
    giftType: '',
    submitDate: new Date().toISOString().split('.')[0],
    content: '',
    status: 0
})

// 表单验证规则（根据网页5的规范增强）
const formRules = {
    customer: [
        { required: true, message: '请输入投诉人姓名', trigger: 'blur' },
        { min: 2, max: 10, message: '姓名长度2-10个字符' }
    ],
    giftType: [{ required: true, message: '请选择礼物类型', trigger: 'change' }],
    submitDate: [{ required: true, message: '请选择提交时间', trigger: 'change' }],
    content: [
        { required: true, message: '请填写投诉内容', trigger: 'blur' },
        { min: 20, max: 200, message: '内容长度20-200个字符' }
    ],
    status: [{ required: true, message: '请选择处理状态', trigger: 'change' }]
}

// 操作函数（根据网页3的流程优化）
const handleAdd = () => {
    isEditMode.value = false
    resetForm()
    dialogVisible.value = true
}

const handleEdit = (row) => {
    isEditMode.value = true
    Object.assign(formData, { ...row })
    dialogVisible.value = true
}

const handleDelete = (id) => {
    ElMessageBox.confirm('确定删除该投诉记录？删除后将不可恢复！', '警告', {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消操作',
        type: 'warning'
    }).then(() => {
        complaints.value = complaints.value.filter(c => c.id !== id)
        ElMessage.success('投诉记录已删除')
    })
}

const submitForm = async () => {
    await formRef.value.validate()
    if (isEditMode.value) {
        const index = complaints.value.findIndex(c => c.id === formData.id)
        complaints.value.splice(index, 1, { ...formData })
    } else {
        complaints.value.push({
            ...formData,
            id: Date.now(),
            submitDate: formData.submitDate || new Date().toISOString().split('.')[0]
        })
    }
    dialogVisible.value = false
}

const resetForm = () => {
    formData.id = null
    formData.complaintId = ''
    formData.customer = ''
    formData.giftType = ''
    formData.submitDate = new Date().toISOString().split('.')[0]
    formData.content = ''
    formData.status = 0
}
</script>

<style scoped>
.complaint-management {
    padding: 20px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.operation-bar {
    margin-bottom: 20px;
    display: flex;
    gap: 15px;
}

.el-table {
    margin-top: 20px;
}

.el-tag {
    font-weight: 500;
}

.el-textarea__inner {
    height: 80px;
}
</style>